package casa.depesos.app.com.frag;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.SPHelper;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.util.List;

import casa.depesos.app.com.activity.BaseActivity;
import casa.depesos.app.com.activity.ChangePwdActivity;
import casa.depesos.app.com.activity.LoginActivity;
import casa.depesos.app.com.databinding.FragmentForgetPhoneBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.RightDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.req.IsRegReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class ForgetPhoneFragment extends BaseFragment {

    FragmentForgetPhoneBinding binding;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_FF_001");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentForgetPhoneBinding.inflate(inflater, container, false);
        binding.top.top.setPadding(0, Utils.getStatusBarHeight(getActivity()), 0, 0);
        binding.top.title.setText("Olvidé mi contraseña");
        binding.top.back.setOnClickListener(v -> {
            if (getActivity() instanceof LoginActivity) {
                ((LoginActivity) getActivity()).removeFragment(this);
            } else if (getActivity() instanceof ChangePwdActivity) {
                getActivity().finish();
            }
        });
        binding.next.setOnClickListener(v -> next());
        Utils.setNumberEditTextInputSpace(binding.phone, 10);
        binding.phone.addTextChangedListener(new TextWatcher() {
            boolean report = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int len = s.toString().length();
                if (len > 0 && !report) {
                    report = true;
                    reportInputPhone();
                }
                binding.clear.setVisibility(len > 0 ? View.VISIBLE : View.INVISIBLE);
                binding.next.setEnabled(len == 10);
                if (len == 10) {
                    binding.next.setAlpha(1);
                } else {
                    binding.next.setAlpha(0.6f);
                }
            }
        });
        binding.clear.setOnClickListener(v -> binding.phone.setText(""));

        return binding.getRoot();
    }

    protected void reportInputPhone() {
        Report.click("ACTION_FF_002");
    }

    private void next() {
        String p = binding.phone.getText().toString().trim();
        if (p.length() != 10) {
            ToastUtil.showShortToast(getActivity(), "Ingrese un número telefónico válido de 10 dígitos");
            return;
        }
        showLoading();
        Report.click("ACTION_FF_003");
        new IsRegReq(p).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    if ("0".equals(bean.getCode())) {//未注册
                        toReg();
                    } else {
                        jump(p);
                    }
                }
            }
        });
    }

    protected void jump(String p) {
        String key = "agree1";
        if (Constant.white || SPHelper.getInstance(getActivity()).getBoolean(key, false)) {
            jump(true, p);
        } else {
            new RightDlg().setSms().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        SPHelper.getInstance(getActivity()).putBooleanAndCommit(key, true);
                    }
                    jump(isOk, p);
                }
            }).show(getChildFragmentManager(), "");
        }
    }

    protected void jump(boolean agree, String phone) {
        if (!Constant.white && agree) {
            XXPermissions.with(this)
                    .permission(Permission.READ_SMS, Permission.RECEIVE_SMS)
                    .request(new OnPermissionCallback() {
                        boolean deal = false;

                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            if (allGranted) {
                                toCode(true, phone);
                            } else {
                                onDenied();
                            }
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                            onDenied();
                        }

                        void onDenied() {
                            if (deal) {
                                return;
                            }
                            deal = true;
                            toCode(true, phone);
                        }
                    });
        } else {
            toCode(false, phone);
        }
    }

    private boolean doubleCheck(boolean bo) {
        if (!Utils.isXm()) {
            return bo;
        }
        // 读取一下试试，能读取到就有权限
        try {
            Uri uri = Uri.parse("content://sms/inbox");
            ContentResolver cr = getActivity().getContentResolver();
            String[] projection = new String[]{"_id"};
            Cursor cur = cr.query(uri, projection, null, null, "date desc");
            if (null != cur) {
                cur.close();
            }
            return bo;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    protected void toCode(boolean hasRight, String phone) {
        hasRight = doubleCheck(hasRight);
        if (getActivity() instanceof LoginActivity) {
            ((LoginActivity) getActivity()).toForgetCode(phone, hasRight);
            ((BaseActivity) getActivity()).removeFragment(this);
        } else if (getActivity() instanceof ChangePwdActivity) {
            ((ChangePwdActivity) getActivity()).toForgetCode(phone, hasRight);
        }
    }

    private void toReg() {
        ToastUtil.showShortToast(getActivity(), "El número telefónico no está registrado");
        if (getActivity() instanceof LoginActivity) {
            ((LoginActivity) getActivity()).changeWay(binding.phone.getText().toString().trim());
        }
    }
}
